<template>
  <div class="container">
    <h2>用户注册</h2>
    <form @submit.prevent="handleRegister">
      <!-- 用户名 -->
      <div class="form-group">
        <label for="userName">用户名：</label>
        <input 
          type="text" 
          id="userName" 
          name="userName" 
          v-model="registerForm.userName" 
          placeholder="请输入用户名" 
          required 
        >
      </div>

      <!-- 邮箱 + 验证码按钮 -->
      <div class="verification-code">
        <input 
          type="email" 
          id="email" 
          name="email" 
          v-model="registerForm.email" 
          placeholder="请输入邮箱" 
          @blur="validateEmail"
          required 
        >
        <button 
          type="button" 
          id="sendCodeBtn" 
          @click="sendVerificationCode" 
          :disabled="isSendingCode || isCountingDown || !emailValid"
        >
          {{ buttonText }}
        </button>
      </div>

      <!-- 验证码 -->
      <div class="form-group">
        <label for="verifyCode">验证码：</label>
        <input 
          type="text" 
          id="verifyCode" 
          name="verifyCode" 
          v-model="registerForm.verifyCode" 
          placeholder="请输入验证码" 
          @blur="validateVerifyCode"
          required 
        >
        <p class="error-tip" v-if="verifyCodeError">{{ verifyCodeError }}</p>
      </div>

      <!-- 密码 -->
      <div class="form-group">
        <label for="password">密码：</label>
        <input 
          type="password" 
          id="password" 
          name="password" 
          v-model="registerForm.password" 
          placeholder="请输入密码" 
          required 
        >
      </div>

      <!-- 确认密码 -->
      <div class="form-group">
        <label for="confirmPassword">确认密码：</label>
        <input 
          type="password" 
          id="confirmPassword" 
          name="confirmPassword" 
          v-model="confirmPassword" 
          placeholder="请确认密码" 
          @input="validatePasswords"
          required 
        >
        <p class="error-tip" v-if="passwordError">{{ passwordError }}</p>
      </div>

      <!-- 注册按钮 -->
      <button type="submit" class="btn" :disabled="loading || !isFormValid">
        {{ loading ? '注册中...' : '注册' }}
      </button>

      <!-- 登录跳转 -->
      <div class="links">
        <router-link to="/login">已有账号？立即登录</router-link>
      </div>
      <div v-if="errorMessage" class="error-message">{{ errorMessage }}</div>
    </form>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  data() {
    return {
      registerForm: {
        userName: '',
        email: '',
        password: '',
        verifyCode: ''
      },
      confirmPassword: '',
      loading: false,
      errorMessage: '',
      // 验证码相关
      isSendingCode: false,
      isCountingDown: false,
      countdown: 60,
      buttonText: '获取验证码',
      verifyCodeError: '',
      verifyCodeValid: null, // null:未验证 | true:通过 | false:失败
      // 验证状态
      emailValid: null,
      passwordValid: null,
      passwordError: '',
      returnVerifyCode: ''
    };
  },
  computed: {
    // 表单是否可提交（所有验证通过）
    isFormValid() {
      return (
        this.registerForm.userName &&
        this.emailValid &&
        this.registerForm.verifyCode &&
        this.verifyCodeValid &&
        this.registerForm.password &&
        this.confirmPassword &&
        this.passwordValid
      );
    }
  },
  methods: {
    // 验证邮箱格式
    validateEmail() {
      const regex = /^[\w.-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$/;
      this.emailValid = regex.test(this.registerForm.email);
    },
    // 发送验证码（已修复冷却功能）
    async sendVerificationCode() {
      if (this.isSendingCode || this.isCountingDown || !this.emailValid) return;
      this.isSendingCode = true;
      this.errorMessage = '';

      try {
        // 修复路径：移除多余的 /api
        const res = await axios.post('api/email/auth/sendCode', null, {
          params: {
            email: this.registerForm.email,
            typeCode: 'register'
          }
        });
        
        if (res.data.code !== 200) throw new Error(res.data.message);
        
        this.returnVerifyCode = res.data.data;
        
        // 启动倒计时
        this.startCountdown();
      } catch (err) {
        this.errorMessage = err.message || '发送失败，请重试';
      } finally {
        this.isSendingCode = false;
      }
    },
    // 倒计时逻辑（优化）
    startCountdown() {
      this.isCountingDown = true;
      this.countdown = 60;
      this.buttonText = `${this.countdown}s后重试`;
      
      const timer = setInterval(() => {
        this.countdown--;
        this.buttonText = `${this.countdown}s后重试`;
        
        if (this.countdown <= 0) {
          clearInterval(timer);
          this.isCountingDown = false;
          this.buttonText = '获取验证码';
        }
      }, 1000);
    },
    // 验证验证码（模拟接口，需后端支持）
    async validateVerifyCode() {
      if (!this.registerForm.verifyCode) {
        this.verifyCodeValid = null;
        return;
      }

      try {
        this.verifyCodeValid = this.returnVerifyCode == this.registerForm.verifyCode;
        if (!this.verifyCodeValid) {
          this.verifyCodeError = '验证码错误';
        }
      } catch (err) {
        this.verifyCodeError = '验证失败，请重试';
        this.verifyCodeValid = false;
      }
    },
    // 验证密码一致性
    validatePasswords() {
      this.passwordValid = (this.registerForm.password === this.confirmPassword);
      this.passwordError = this.passwordValid ? '' : '两次密码不一致';
    },
    // 注册提交
    async handleRegister() {
      if (!this.isFormValid) return;
      this.loading = true;

      try {
        const res = await axios.post('/api/login/register', this.registerForm);
        if (res.data.code !== 200) throw new Error(res.data.message);
        
        // 注册成功跳转（示例）
        this.$router.push({
          path: '/registerSuccess',
          query: { email: this.registerForm.email }
        });
      } catch (err) {
        this.errorMessage = err.message || '注册失败，请重试';
      } finally {
        this.loading = false;
      }
    }
  }
};
</script>

<style src="../../assets/Reset.css">
</style>